package org.altervista.cp.microkernel.log;

import java.util.LinkedList;

public class LogContext {

	private static final ThreadLocal<LinkedList<LogContext>> _logContextTL = new ThreadLocal<LinkedList<LogContext>>() {
		protected LinkedList<LogContext> initialValue() {
			return new LinkedList<LogContext>();
		}
	};

	public static final LogContext DEFAULT = new LogContext("default");

	public static final LogContext openLogContext(String logContext) {
		return new LogContext(logContext);
	}

	public void close() {
		if (this != DEFAULT) {
			_logContextTL.get().remove(this);
		}
	}

	public String toString() {
		return _logContext;
	}

	public static final LogContext currentLogContext() {
		LinkedList<LogContext> lcList = _logContextTL.get();
		LogContext lc = lcList.isEmpty() ? null : lcList.getLast();
		return lc == null ? DEFAULT : lc;
	}

	private LogContext(String logContext) {
		if (DEFAULT != null && logContext.equals(DEFAULT.toString())) {
			throw new IllegalArgumentException("'" + logContext
					+ "' is the name of the default log context");
		}
		_logContext = logContext;
		_logContextTL.get().add(this);
	}

	private String _logContext;

}